//
//  ViewController.m
//  3DES
//
//  Created by mimi on 17/4/19.
//  Copyright © 2017年 mimi. All rights reserved.
//

#import "ViewController.h"
#import "JKEncrypt.h"
#import "GTMBase64.h"
#import <CommonCrypto/CommonCryptor.h>
#import <limits.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSRange.h>
#import <stdarg.h>
#import "NSData+Base64.h"
#import "NSData+CommonCrypto.h"
#import "AESCrypt.h"
#define gkey            @"MAXUS-QRCODE-F987FE57A49S"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  //  JKEncrypt * en = [[JKEncrypt alloc]init];
    //加密
    NSString* key = @"MAXUS-QRCODE-F987FE57A49S";
    NSString* ss = @"Hello Wolrdbgrb htnrgtbrytbnhnn#%U&";
    NSString * encryptStr =  @"fqUfoIxHRR/zoKARZ+yDau2/v3ulexkzg9259zOzWF348fe/c5k9yUKkFVmnoYEAg5e2eFS8xzIdiTaE6vsHuw==";
    
    //NSData *data = [ss dataUsingEncoding:NSUTF8StringEncoding];
    //NSString* base64Str = [data base64EncodedStringWithOptions:0];
   // NSString* pp = [base64Str stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
    
    NSString* de = [self doDecEncryptStr:encryptStr];
    NSLog(@"de:%@",de);

    NSString * kk = [self decryptUseDES:encryptStr key:key];//[self encryptUseDES:ss key:key];
    //NSString * pipi = [[NSString alloc]initWithData:kk encoding:NSUTF8StringEncoding];
   // NSLog(@"密文:%@",pipi);
    
   
   // NSLog(@"=%@",base64Str);
    NSString* str = [self decryptUseDES:encryptStr key:key];
    NSLog(@"=%@",str);
    

}

-(void)demo{
//测试上传
}

-(void)demo2{
    //准备滚到这个版本
}



- (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key
{
    NSData* cipherData = [GTMBase64 decodeString:cipherText];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    Byte iv[] = {1,2,3,4,5,6,7,8};
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String],
                                          kCCKeySize3DES,
                                          iv,
                                          [cipherData bytes],
                                          [cipherData length],
                                          buffer,
                                          1024,
                                          &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return plainText;
}
- (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
{
    NSString *ciphertext = nil;
    const char *textBytes = [plainText UTF8String];
    NSUInteger dataLength = [plainText length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    Byte iv[] = {1,2,3,4,5,6,7,8};
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          iv,
                                          textBytes, dataLength,
                                          buffer, 1024,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        
        ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding] ;
    }
    return ciphertext;
}






////////
//- (NSString *)encryptUseDES:(NSString *)plainText andKey:(NSString *)authKey andIv:(NSString *)authIv{
//    const voidvoid *iv  = (const voidvoid *) [authIv UTF8String];
//    NSString *ciphertext = nil;
//    NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
//    NSUInteger dataLength = [textData length];
//    unsigned char buffer[1024];
//    memset(buffer, 0, sizeof(char));
//    size_t numBytesEncrypted = 0;
//    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
//                                          kCCAlgorithmDES,
//                                          kCCOptionPKCS7Padding,
//                                          [authKey UTF8String],
//                                          kCCKeySizeDES,
//                                          iv,
//                                          [textData bytes],
//                                          dataLength,
//                                          buffer,
//                                          1024,
//                                          &numBytesEncrypted);
//    if (cryptStatus == kCCSuccess) {
//        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
//        NSString *oriStr = [NSString stringWithFormat:@"%@",data];
//        NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@"< >"];
//        ciphertext = [[oriStr componentsSeparatedByCharactersInSet:cSet] componentsJoinedByString:@""];
//    }
//    return ciphertext;
//}


-(NSData*) encryptText:(NSString*)text {
    CCCryptorStatus status = kCCSuccess;
    NSData* result = [[text dataUsingEncoding:NSUTF8StringEncoding]
                      dataEncryptedUsingAlgorithm:kCCAlgorithmAES128
                      key:[self getAesKey]
                      initializationVector:nil   // ECB加密不会用到iv
                      options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
                      error:&status];
    if (status != kCCSuccess) {
     //   DLog(@"加密失败:%d", status);
        return nil;
    }
    return result;
}
-(NSString*)getAesKey{
    return @"MAXUS-QRCODE-0987FE55623";
}

-(NSString*)doDecEncryptStr:(NSString *)encryptStr{
    
    NSData *encryptData = [GTMBase64 decodeData:[encryptStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    size_t plainTextBufferSize = [encryptData length];
    const void *vplainText = [encryptData bytes];
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [gkey UTF8String];
    
    //    const void *vinitVec = (const void *) [gIv UTF8String];
    
    ccStatus = CCCrypt(kCCDecrypt,
                       kCCAlgorithm3DES,
                       kCCOptionPKCS7Padding|kCCOptionECBMode,
                       vkey,
                       kCCKeySize3DES,
                       nil,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    
    NSString *result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                                     length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding];
    
    
    return result;
}



//-(NSData *)EncyptPCK5WithData:(NSData *)encyptData WithKey:(NSString *)key WithError:(NSError **)error {
//    
//    Byte *encyByte=(Byte *)[encyptData bytes];
//    
//    if (error!=nil) {
//        *error=nil;
//    }
//    
//    NSMutableData *returnData=[[NSMutableData alloc] init];
//    
//    NSData *desKey = [key dataUsingEncoding:NSUTF8StringEncoding];
//    {
//        if ([desKey length]==16||[desKey length]==24) {
//            unsigned char *src = NULL; /* 补齐后的明文 */
//            unsigned char temp[8];
//            unsigned char block_key[9];
//            Byte *key;
//            DES_key_schedule ks,ks2,ks3;
//            int reLen;
//            
//            reLen=8-[encyptData length]%8;
//            
//            src=malloc([encyptData length]+reLen);
//            
//            
//            unsigned char ch;
//            
//            ch = reLen;
//            int len = [encyptData length]+reLen;
//            memset(src, 0, len);
//            memcpy(src, encyByte, [encyptData length]);
//            memset(src + [encyptData length], ch, reLen);
//            
//            
//            key=(Byte *)[desKey bytes];
//            memcpy(block_key, key + 0, 8);
//            DES_set_key_unchecked((const_DES_cblock*)block_key, &ks);
//            memcpy(block_key, key + 8, 8);
//            DES_set_key_unchecked((const_DES_cblock*)block_key, &ks2);
//            if ([desKey length]==24) {
//                memcpy(block_key, key + 16, 8);
//                DES_set_key_unchecked((const_DES_cblock*)block_key, &ks3);
//            }
//            else {
//                memcpy(block_key, key + 0, 8);
//                DES_set_key_unchecked((const_DES_cblock*)block_key, &ks3);
//                
//            }
//            
//            int count =(reLen+(int)[encyptData length])/ 8;
//            for (int i = 0; i < count; i++)
//            {
//                memset(temp, 0, 8);
//                /* 加密 */
//                DES_ecb3_encrypt((const_DES_cblock*)(src+8*i), (DES_cblock*)temp, &ks, &ks2, &ks3, DES_ENCRYPT);
//                [returnData appendBytes:temp length:sizeof(temp)];
//                
//            }
//            free(src);
//            
//        }
//        else {
//            if (error!=nil) {
//                //                *error=[ErrorCode DesError];
//            }
//        }
//        
//    }
//    
//    return returnData;
//}


@end
